package org.summerframework.component.security.controller;


import org.summerframework.component.security.LoginData;
import org.summerframework.component.security.context.RequestContext;
import org.summerframework.component.security.context.RequestContextFactory;
import org.summerframework.core.util.UrlUtil;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 基础控制类
 *
 * @author 石超
 * @version v1.0.0
 */
public abstract class BaseController extends ServletRequestUtils {
    public final static String RESULT_BASE = "json/success";
    public final static String RESULT_VAR = "result";
    public final static String URL_UTIL = "urlUtil";
    public final static String REQUEST_CONTEXT = "requestContext";
    public final static String ERROR_URL = "error_url";
    public final static String ERROR_BUTTON = "error_button";
    public final static String DATA_VAR = "data";

    protected <T> LoginData<T> getLoginData() {
        return RequestContextFactory.getLoginData();
    }

    @ModelAttribute(REQUEST_CONTEXT)
    protected <T> RequestContext<T> getContext() {
        return RequestContextFactory.getCurrentContext();
    }

    public Boolean isPermissions(String permissions) {
        return getContext().isPermissions(permissions);
    }


    /**
     * 重定向url
     */
    public void redirect(String url) throws IOException {
        getContext().getResponse().sendRedirect(url);
    }

    /**
     * 转发url
     */
    public String forward(String url) {
        return "forward:" + url;
    }


    public Long getUserId() {
        return getLoginData().getUserId();
    }

    public boolean isAny() {
        return getContext().getIsAny();
    }

    public <T> T getUser() {
        return this.<T>getLoginData().getUser();
    }

    @ModelAttribute("callback")
    public String getCallback(String callback) {
        return callback;
    }

    @ModelAttribute(URL_UTIL)
    public Map<String, String> getUrlUtil() {
        return UrlUtil.getUrl();
    }


    /**
     * 输出html页面
     *
     * @param html
     */
    public void returnHtml(String html) {
        getContext().getResponse().setContentType("text/html;charset=UTF-8");

        try (PrintWriter writer = getContext().getResponse().getWriter()) {
            writer.write(html);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
